package com.qipa.netty.handler;

import com.qipa.common.ResultModel;
import com.qipa.netty.common.HttpConstant;
import com.qipa.netty.service.HandlerService;
import com.qipa.netty.util.HttpUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
public class HealthServerHandler extends ChannelInboundHandlerAdapter {

    Logger logger = Logger.getLogger(HealthServerHandler.class);


    private final String wsUri;

    @Autowired
    HandlerService handlerService;


    public HealthServerHandler() {
        this.wsUri = "/ws";
    }

    public HealthServerHandler(String wsUri) {
        this.wsUri = wsUri;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //客户端连接会来这里
        logger.info(ctx.channel().localAddress()+"客户端连上了...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//        logger.info("有客户端关闭连接");
        super.channelInactive(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        if (msg instanceof TextWebSocketFrame) {
            //TextWebSocketFrame
            TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
            logger.info(textWebSocketFrame.text());

        } else if (msg instanceof FullHttpRequest) {
            //http请求
            FullHttpResponse response = null;
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;

            if (wsUri.equalsIgnoreCase(fullHttpRequest.uri())) {
                //todo websocket进来，连接socket，因为连接socket其实是http协议
                //如果是WebSocket请求，则保留数据并传递到下一个ChannelHandler
                ctx.fireChannelRead(fullHttpRequest.retain());
            } else {
                FullHttpRequest req = (FullHttpRequest) msg;//客户端的请求对象
                JSONObject responseJson = new JSONObject();//新建一个返回消息的Json对象
                ResultModel resultModel = new ResultModel();
                if (fullHttpRequest.method() == HttpMethod.GET) {
                    //todo get请求
                    //删除http连接

                    switch (com.qipa.netty.util.HttpUtil.checkType(fullHttpRequest)) {
                        case HttpConstant.GET_PUSH_CHAT:    /*上报聊天记录*/
                            resultModel = handlerService.pushChat(ctx, fullHttpRequest);
                            break;
                    }
                    HttpUtil.responseJson(ctx, req, JSONObject.fromObject(resultModel).toString());
                    return;
                } else if (fullHttpRequest.method() == HttpMethod.POST) {
                    //todo post请求
                    //把客户端的请求数据格式化为Json对象
                    JSONObject requestJson = null;
                    try {
                        requestJson = JSONObject.fromObject(HttpUtil.parseJosnRequest(req));
                    } catch (Exception e) {
                        HttpUtil.responseJson(ctx, req, new String("error json"));
                        return;
                    }
                    String uri = req.uri();//获取客户端的URL
                    //根据不同的请求API做不同的处理(路由分发)，只处理POST方法
                    if (req.method() == HttpMethod.POST) {

                    } else {
                        //错误处理
                        responseJson.put("error", "404 Not Find");
                    }
                } else {
                    //非get和非post
                    response = HttpUtil.responseOK(HttpResponseStatus.INTERNAL_SERVER_ERROR, null);
                }

                //向客户端发送结果
                HttpUtil.responseJson(ctx, req, responseJson.toString());
            }
        } else if (msg instanceof WebSocketFrame) {
            //todo 如果是Websocket请求，则进行websocket操作
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }


    //处理Websocket的代码
    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        //如果是WebSocket请求，则保留数据并传递到下一个ChannelHandler
        ctx.fireChannelRead(frame.retain());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }


}
